package com.beiding.config;

import com.beiding.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurationSupport;

import java.security.Principal;

@Configuration
public class StompConfig extends WebSocketMessageBrokerConfigurationSupport {


    private MessageService service;


    @Autowired
    public void setService(MessageService service) {
        this.service = service;
    }



    /*

         如果使用基于内存实现认证Websocket就能够连接成功,而使用自定义的方式就会失败

     */

    @Override
    protected void configureClientInboundChannel(ChannelRegistration registration) {

        registration.interceptors(new ChannelInterceptor() {

            @Override
            public Message<?> preSend(Message<?> message, MessageChannel channel) {


                StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);


                System.out.println(accessor.getCommand());


                Principal user = (Principal) accessor.getHeader(SimpMessageHeaderAccessor.USER_HEADER);

                System.out.println(user.getName());

                if (StompCommand.CONNECT.equals(accessor.getCommand())) {

                    if (user != null) {
                        service.online(user.getName());
                    }

                    //这是不可靠的,在zuul层关闭的时候就不能收到用户下线的提醒.实际上用户已经关闭下线了
                    //但是数据库中仍然标记着该用户处于上线状态.就会出现逻辑上的错误

                    //考虑限制多登录

                } else if (StompCommand.DISCONNECT.equals(accessor.getCommand())) {//如果断开连接
                    if (user != null && accessor.getHeader(StompHeaderAccessor.STOMP_HEARTBEAT_HEADER) == null)
                        service.offline(user.getName());
                }


                return message;

            }

            @Override
            public void postSend(Message<?> message, MessageChannel channel, boolean sent) {
                StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);

                if (StompCommand.SUBSCRIBE.equals(accessor.getCommand())) {
                    Principal user = (Principal) accessor.getHeader(SimpMessageHeaderAccessor.USER_HEADER);
                    if (user != null) {
                        service.subscribe(user.getName(), accessor.getDestination());
                    }

                }
            }
        });

    }

    @Override
    protected void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/message").setAllowedOrigins("*").withSockJS();
    }

    @Override
    protected void configureMessageBroker(MessageBrokerRegistry registry) {
        super.configureMessageBroker(registry);
        registry.setApplicationDestinationPrefixes("/app");
        registry.enableSimpleBroker("/queue", "/topic");
    }


}


//如果是用户手动断开连接,那么断开连接的时候会初恋两次Disconnect命令,一次含有STOMP_HEARTBEAT_HEADER,另一次则不含有


//使用websocket要使用security,这样当用户订阅/user/**的时候才能知道这个用户是谁(基于Principal)
// 如果没有user则可以使用 accessor.setUser()来设置.


